package com.wonders.bigdata.nio.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

/**
 * Description: <br>
 *     1.SimpleChannelInboundHandler是ChannelInboundHandlerAdapter的子类
 *     2.HttpObject客户端和服务器端相互通讯的数据被封装的对象
 *
 * @author: XB
 * @date: 2021/6/21 10:55
 */
public class TestHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, HttpObject httpObject) throws Exception {
        // 判断httpObject是不是HttpRequest请求
        if (httpObject instanceof HttpRequest) {
            System.out.println("httpObject类型 = " + httpObject.getClass());
            System.out.println("客户端地址" + channelHandlerContext.channel().remoteAddress());

            //回复信息给浏览器（http协议）
            ByteBuf content = Unpooled.copiedBuffer("hello，我是服务器", CharsetUtil.UTF_8);

            //构造一个http的响应，即httpResponse
            DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);
            response.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain");
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());

            // 将构建好的response返回
            channelHandlerContext.writeAndFlush(response);
        }
    }
}
